<template>
  <div class="rectification-template">
    <!--    模板列表 start  -->
    <div class="template-container">
      <div class="template-list">
        <template v-for="(item, index) in templateList" :key="item.packageId">
          <div v-if="item.isAddOrEdit" class="template-item template-edit">
            <a-input v-model="item.packageName" v-auto-focus @keyup.enter="handelSubmitTemplate(item)" />
            <div class="template-item-icon">
              <GiSvgIcon
                name="rectification-submit"
                size="16"
                style="margin-right: 10px"
                @click="handelSubmitTemplate(item)"
              ></GiSvgIcon>
              <GiSvgIcon name="rectification-del" size="16" @click="handelDelTemplate(item, index)"></GiSvgIcon>
            </div>
          </div>
          <div class="template-item" :class="{ 'item-active': item.packageId == activePackageId }" v-else>
            <div class="template-item-label">
              <span @click="handelClickTemplate(item)" v-ellipsis="{ rows: 1, text: item.packageName }" />
            </div>
            <div class="template-item-icon">
              <GiSvgIcon
                name="rectification-edit"
                size="16"
                style="margin-right: 10px"
                @click="handelEditTemplate(item)"
              ></GiSvgIcon>
              <GiSvgIcon name="rectification-del" size="16" @click="handelDelTemplate(item) as any"></GiSvgIcon>
            </div>
          </div>
        </template>
      </div>
      <div class="template-button">
        <a-button type="primary" @click="handelAddTemplate">
          <template #icon>
            <icon-plus />
          </template>
          添加模板
        </a-button>
      </div>
    </div>
    <!--    模板列表 end  -->

    <!-- 任务列表 start  -->
    <div class="app-container task-container">
      <div class="task-header">
        <a-button type="primary" @click="handelAddTask" :disabled="!activePackageId">
          <template #icon>
            <icon-plus />
          </template>
          增加任务
        </a-button>
      </div>
      <a-table
        :data="taskList"
        :columns="templateColumns as any"
        :pagination="false"
        :stripe="true"
        :scroll="{ x: '130%', y: '100%' }"
      >
        <template #isMust="{ record }">
          <span>{{ record.isMust ? "是" : "否" }}</span>
        </template>
        <template #status="{ record }">
          <a-switch v-model="record.status" :unchecked-value="0" :checked-value="1" @change="handelChangeTaskStatus(record)" />
        </template>
        <template #operate="{ record }">
          <a-button type="text" size="mini" @click="handelEditTask(record.taskSettingId)">编辑</a-button>
          <a-button type="text" size="mini" @click="handleReferenceData(record)">参考数据</a-button>
          <a-button type="text" size="mini" @click="handelDelTask(record)">删除</a-button>
        </template>
      </a-table>
    </div>
    <!-- 任务列表 end  -->

    <!--  删除模板  -->
    <a-modal
      :visible="isShowDelModal"
      @ok="handleDelOk"
      @cancel="handleDelCancel"
      okText="确定"
      cancelText="取消"
      width="400px"
      :mask-closable="false"
      unmountOnClose
      :closable="false"
    >
      <div class="modal-message">
        <div class="del-name">{{ delData.packageName }}</div>
        <div class="del-tip">确定删除该模板吗？</div>
      </div>
    </a-modal>

    <!--  任务模板配置 start  -->
    <a-drawer
      :visible="isShowTaskOption"
      :width="900"
      :header="false"
      unmountOnClose
      @ok="handelSubmitTaskOk"
      @cancel="handelCloseTaskDrawer"
    >
      <div class="drawer-content">
        <CustomTitle :title="(isNew ? '添加' : '编辑') + '任务'" />
        <a-form :model="processForm" ref="processFormRef">
          <a-space>
            <a-form-item
              label="任务名称"
              field="taskName"
              :rules="[...rules, { maxLength: 15, message: '长度不能超过15个字符' }]"
            >
              <a-input v-model="processForm.taskName" />
            </a-form-item>
            <a-form-item
              label="排序号"
              field="orderNum"
              :rules="[...rules, { match: /^[1-9]\d{0,9}$/, message: '请输入大于0但小于10位的正整数' }]"
            >
              <a-input-number v-model="processForm.orderNum" />
            </a-form-item>
          </a-space>
          <a-space>
            <a-form-item label="责任人" field="roleId" :rules="{ required: true, message: '请选择' }">
              <a-select v-model="processForm.roleId">
                <a-option v-for="item in leaderList" :key="item.roleId" :value="item.roleId">
                  {{ item.roleName }}
                </a-option>
              </a-select>
            </a-form-item>
            <a-form-item label="前置条件" field="beforeFieldId">
              <div class="before-condition">
                <div class="link" @click="showBeforeCondition">
                  <icon-plus-circle-fill size="20" />
                  设置（{{ preConditionList.length }}）
                </div>
              </div>
            </a-form-item>
          </a-space>
          <a-space>
            <a-form-item label="间隔天数" field="intervalDays">
              <a-input-number v-model="processForm.intervalDays" :min="0" :max="1000000000" :precision="0" />
            </a-form-item>
            <a-form-item label="关联表单" field="formId" :rules="{ required: true, message: '请选择' }">
              <SelectSearch
                :defaultSelectId="processForm.formId"
                :default-select-list="defaultSelectFormList"
                :requestApi="getSelectFormList"
                :config="searchFormConfig"
                @change-select="changeForm"
              />
            </a-form-item>
          </a-space>
          <a-space>
            <a-form-item
              label="标准天数"
              field="executeDays"
              :rules="[...rules, { match: /^([1-9]|[12][0-9]|30)$/, message: '请输入1-30的正整数' }]"
            >
              <a-input-number v-model="processForm.executeDays" />
            </a-form-item>
            <a-form-item label="跟进周期" field="trackDays">
              <a-input-number v-model="processForm.trackDays" :min="0" :max="1000000000" :precision="0" />
            </a-form-item>
          </a-space>
          <a-space>
            <a-form-item label="是否外出" field="isOut" :rules="{ required: true, message: '请选择' }">
              <a-radio-group v-model="processForm.isOut">
                <a-radio :value="1">是</a-radio>
                <a-radio :value="0">否</a-radio>
              </a-radio-group>
            </a-form-item>
            <a-form-item label="任务执行" field="workDateType">
              <a-radio-group v-model="processForm.workDateType">
                <a-radio :value="1">所有日期</a-radio>
                <a-radio :value="2">只在工作日</a-radio>
              </a-radio-group>
            </a-form-item>
          </a-space>
          <a-space>
            <a-form-item label="是否验收" field="checkType">
              <div class="is-acceptance" :style="{ height: processForm.checkType.length ? 'auto' : '40px' }">
                <a-checkbox-group v-model="processForm.checkType">
                  <a-checkbox :value="1">内部</a-checkbox>
                  <a-checkbox :value="2">客户</a-checkbox>
                </a-checkbox-group>
                <div class="select" v-if="processForm.checkType.length">
                  <a-cascader
                    :options="templateTree"
                    @change="changeAcceptance as any"
                    v-model="processForm.standardId"
                    :field-names="fieldNames"
                    placeholder="请选择"
                  />
                </div>
              </div>
            </a-form-item>
            <a-form-item label="是否启用" field="status">
              <a-switch v-model="processForm.status" :unchecked-value="0" :checked-value="1" />
            </a-form-item>
          </a-space>
          <a-space>
            <a-form-item
              label="审批通过才进行下一步"
              field="isAudit"
              :class="[processForm.checkType.length > 0 ? 'top-distance' : '']"
            >
              <a-switch v-model="processForm.isAudit" :unchecked-value="false" :checked-value="true" />
            </a-form-item>
            <a-form-item
              v-if="preConditionList.length > 0"
              label="指派时间"
              field="assignTimeType"
              :class="[processForm.checkType.length > 0 ? 'top-distance' : '']"
            >
              <a-checkbox v-model="processForm.assignTimeType">该任务可设置后置任务计划开始时间</a-checkbox>
            </a-form-item>
          </a-space>
        </a-form>
        <div class="desc">操作说明</div>
        <QuillEditor v-model:content="processForm.remark" :toolbar="toolbar" contentType="html" ref="myQuillEditor" />
        <input
          type="file"
          name="file"
          @change="changeImage"
          ref="uploadFileImage"
          style="opacity: 0; width: 0; height: 0; cursor: pointer"
        />
      </div>
    </a-drawer>
    <!--  任务模板配置 end  -->
    <!--  start 前置条件-->
    <a-modal v-model:visible="conditionVisible" hide-title>
      <CustomTitle title="设置前置条件" />
      <div class="condition-list">
        <div class="condition-item" v-for="(item, index) in preConditionList" :key="item">
          <a-row>
            <a-col :span="22">
              <div class="content">
                <div class="condition-label">前置流程</div>
                <a-select
                  @change="changeBeforeTaskSetting($event, item) as any"
                  @clear="handelClearBeforeTask(item)"
                  allow-clear
                  v-model="item.beforeTaskSettingId"
                  placeholder="请选择"
                >
                  <a-option
                    v-for="processItem in beforeTaskList"
                    :value="processItem.taskSettingId"
                    :key="processItem.taskSettingId"
                    >{{ processItem.taskName }}
                  </a-option>
                </a-select>
              </div>
              <div class="content">
                <div class="condition-label">前置条件</div>
                <a-select
                  v-model="item.beforeFieldId"
                  placeholder="请选择"
                  @change="changeBeforeField($event, item) as any"
                  @clear="handelClearBeforeField(item)"
                  allow-clear
                >
                  <a-option v-for="beforeItem in item.beforeFields" :value="beforeItem.id" :key="beforeItem.id"
                    >{{ beforeItem.title }}
                  </a-option>
                </a-select>
                <a-select style="margin-left: 10px" v-model="item.beforeFieldVal" placeholder="请选择" allow-clear>
                  <a-option v-for="fieldItem in item.beforeFieldOptions" :value="fieldItem" :key="fieldItem"
                    >{{ fieldItem }}
                  </a-option>
                </a-select>
              </div>
            </a-col>
            <a-col :span="2">
              <div class="delete" @click="delBeforeCondition(index)">
                <icon-delete size="18" />
              </div>
            </a-col>
          </a-row>
        </div>
        <div class="add-item" @click="addBeforeCondition">
          <icon-plus-circle-fill size="20" />
          <span>添加</span>
        </div>
      </div>
      <template #footer>
        <div class="btn-footer">
          <a-button @click="conditionVisible = false">取消</a-button>
          <a-button type="primary" @click="beforeConditionConfirm">确定</a-button>
        </div>
      </template>
    </a-modal>
    <referenceData v-if="showReferenceDialog" :task-setting-id="taskSettingId" @handleReferenceClose="handleReferenceClose">
    </referenceData>
  </div>
</template>

<script setup lang="ts">
import { ref, getCurrentInstance } from "vue";
import { Message } from "@arco-design/web-vue";
import { cloneDeep } from "lodash";
import { templateColumns } from "./configData";
import * as templateApi from "@/apis/taskTemplate";
import { formFieldByFormId, getFormList, getOptionList, getSelectFormList, taskDetail } from "@/apis/system";
import { getRoleList } from "@/apis/role";
import { standardTemplateTree } from "@/apis/projectConfig";
import type { TemplateItem, TemplateTaskItem } from "@/apis";
import type { RoleItem, ProcessTaskItem, beforeConditionItem } from "@/apis/system/type";
import CustomTitle from "@/components/CustomTitle/index.vue";
import SelectSearch from "@/components/selectSearch/index.vue";
import referenceData from "../referenceDataDialog/index.vue";

defineProps({
  rules: {
    type: Array,
    default: () => []
  }
});
const { proxy }: any = getCurrentInstance();

/**
 * 模板列表
 */
const templateList = ref<TemplateItem[]>([]);
const activePackageId: any = ref("");
const getTemplateList = async () => {
  const { data } = await templateApi.listTemplate();
  templateList.value = data ?? [];
};
const handelClickTemplate = (data: TemplateItem) => {
  activePackageId.value = data.packageId;
  stageDetail.value = cloneDeep(data);
  getTaskList(data.packageId);
};

/**
 * 新增/编辑模板
 */
// 添加模板
const handelAddTemplate = () => {
  const addItem: any = {
    packageId: "",
    packageName: "",
    isAddOrEdit: true
  };
  templateList.value.push({ ...addItem });
};
// 编辑模板
const handelEditTemplate = (data: any) => {
  data.isAddOrEdit = true;
  isNew.value = false;
};
const handelSubmitTemplate = async (data: any) => {
  if (!data.packageName) return;
  let tipMessage = "添加成功!";
  if (data.packageId && data.isAddOrEdit) {
    tipMessage = "编辑成功!";
    await templateApi.editTemplate(data, data.packageId);
  } else {
    await templateApi.addTemplate(data);
  }
  Message.success(tipMessage);
  getTemplateList();
};

/**
 * 删除模板
 */
const isShowDelModal = ref(false);
const delData = ref<TemplateItem>({} as TemplateItem);
const handelDelTemplate = (data: any, index: number) => {
  if (!data.packageId && data.isAddOrEdit) {
    return templateList.value.splice(index, 1);
  }
  delData.value = cloneDeep(data);
  isShowDelModal.value = true;
};
const handleDelOk = async () => {
  await templateApi.delTemplate(delData.value.packageId);
  Message.success("删除成功!");
  if (activePackageId.value === delData.value.packageId) {
    taskList.value = [];
    activePackageId.value = "";
  }
  getTemplateList();
  handleDelCancel();
};
const handleDelCancel = () => {
  isShowDelModal.value = false;
  delData.value = {} as TemplateItem;
};

/**
 * 任务
 */
const taskList = ref<TemplateTaskItem[]>([]);
const getTaskList = async (packageId: any) => {
  const { data } = await templateApi.taskListByPackageId(packageId);
  taskList.value = data ?? [];
};

const isShowTaskOption = ref(false);
const isNew = ref(true);
const stageDetail = ref<TemplateItem>({});
const initProcessData: any = {
  taskName: "",
  isMust: 1,
  formName: "",
  roleId: "",
  executeDays: 1,
  intervalDays: 0,
  trackDays: 0,
  formId: "",
  status: 1,
  isOut: 0,
  orderNum: 1,
  remark: "",
  workDateType: 1,
  checkType: [],
  standardId: "",
  modelId: "",
  isCheck: 0,
  taskType: 3,
  isAudit: false,
  assignTimeType: false
};
const processForm = ref<ProcessTaskItem>({ ...initProcessData });
const initProcessModal = () => {
  if (!isNew.value) {
    getTaskDetail();
  }
  getLeaderList();
  getFlowList();
  getForm();
  getTemplateTree();
};
const handelAddTask = () => {
  isNew.value = true;
  initProcessModal();
  isShowTaskOption.value = true;
};

const currentTaskSettingId = ref("");
const handelEditTask = async (taskSettingId: string) => {
  if (!taskSettingId) {
    return Message.error("请选择要编辑的任务");
  }
  currentTaskSettingId.value = taskSettingId;
  isNew.value = false;
  initProcessModal();
};

const handelDelTask = async (data: TemplateTaskItem) => {
  await templateApi.delTask(data.taskSettingId);
  getTaskList(stageDetail.value.packageId);
};
const handelChangeTaskStatus = async (data: TemplateTaskItem) => {
  try {
    await templateApi.updateTaskStatus(data.taskSettingId, { status: data.status });
    Message.success("操作成功!");
  } catch (err) {
    data.status = data.status === 1 ? 0 : 1;
  }
};

//获取详情
const getTaskDetail = async () => {
  const { data } = await taskDetail(currentTaskSettingId.value);
  // let taskData = testDetailJson
  let taskData = data;
  let checkTypes: number[] = [];
  (taskData.checkType as string)?.split(",")?.forEach((item: any) => {
    checkTypes.push(item === "内部" ? 1 : 2);
  });
  preConditionList.value = taskData.taskTriggerConditionSettings;
  if (preConditionList.value.length > 0) {
    preConditionList.value.map(item => {
      editFilterOptions(item.beforeTaskFormId, { fieldName: "SelectInput" }, item);
    });
  }
  // 回显关联表单
  defaultSelectFormList.value = [
    {
      formId: taskData.formId,
      formName: taskData.formName
    }
  ];
  processForm.value = {
    ...taskData,
    checkType: checkTypes
  };
  isShowTaskOption.value = true;
};

// 前置任务对应表单字段列表
const editFilterOptions = async (formId: string, params?: { fieldName: string }, item: any) => {
  const { data } = await formFieldByFormId(formId, params);
  item.beforeFields = data ?? [];
  const fieldObj: any = item.beforeFields.find(v => v.id === item.beforeFieldId);
  item.beforeFieldName = fieldObj?.title || "";
  item.beforeFieldOptions = fieldObj?.props?.options || [];
};
/**
 * 获取负责人列表
 */
const leaderList = ref<RoleItem[]>([]);
const getLeaderList = async () => {
  const { data } = await getRoleList();
  leaderList.value = data ?? [];
};
/**
 * 获取表单
 */
const searchFormConfig = {
  label: "formName",
  value: "formId",
  keyword: "formName"
};
const defaultSelectFormList = ref([]) as any;
const formsList = ref([]);
const getForm = async () => {
  const { data } = await getFormList("");
  formsList.value = data ?? [];
};

/**
 * 关联表单
 */
const changeForm = (data: any) => {
  processForm.value.formId = data.formId;
  processForm.value.formName = data.formName;
};
/**
 * 前置流程/表单字段
 */
const beforeTaskList = ref<ProcessTaskItem[]>([]);
const preConditionList = ref<beforeConditionItem[]>([]);
const conditionVisible = ref(false);
const showBeforeCondition = () => {
  conditionVisible.value = true;
};
const beforeConditionConfirm = () => {
  if (preConditionList.value.length > 0) {
    const hasDuplicateSampleTypeId = preConditionList.value.some((item, index, array) => {
      return array.filter(innerItem => innerItem.beforeTaskSettingId === item.beforeTaskSettingId).length > 1;
    });
    if (hasDuplicateSampleTypeId) {
      return Message.error("前置条件不能重复");
    }
    conditionVisible.value = false;
  }
};
// 前置任务列表
const getFlowList = async () => {
  const { data } = await templateApi.optionalBeforeTaskList(activePackageId.value);
  beforeTaskList.value = data ?? [];
  // console.log("11",beforeTaskList.value)
};
// 前置任务对应表单字段列表
const getFormField = async (formId: string, params?: { fieldName: string }, item) => {
  const { data } = await formFieldByFormId(formId, params);
  item.beforeFields = data ?? [];
  item.beforeFieldOptions = [];
};
// 选择前置任务
const changeBeforeTaskSetting = (e: string, item: { beforeFieldId: string; beforeFieldVal: string }) => {
  if (!e) return;
  const taskObj: any = beforeTaskList.value.find(v => v.taskSettingId === e);
  item.beforeFieldId = "";
  item.beforeFieldVal = "";
  getFormField(taskObj.formId, { fieldName: "SelectInput" }, item);
};
// 清除前置任务
const handelClearBeforeTask = (item: any) => {
  item.beforeFields = [];
  item.beforeFieldOptions = [];
  item.beforeFieldId = "";
  item.beforeFieldVal = "";
  item.beforeFieldName = "";
};
// 选择前置字段
const changeBeforeField = (
  e: string,
  item: { beforeFieldName: string; beforeFieldVal: string; beforeFieldOptions: any; beforeFields: any }
) => {
  if (!e) return;
  const fieldObj: any = item.beforeFields.find(v => v.id === e);
  item.beforeFieldName = fieldObj?.title || "";
  item.beforeFieldOptions = fieldObj?.props?.options || [];
  item.beforeFieldVal = "";
};
// 清除前置字段
const handelClearBeforeField = (item: { beforeFieldVal: string; beforeFieldName: string; beforeFieldOptions: any }) => {
  item.beforeFieldOptions = [];
  item.beforeFieldVal = "";
  item.beforeFieldName = "";
};
const addBeforeCondition = () => {
  preConditionList.value.push({});
};
const delBeforeCondition = (index: number) => {
  preConditionList.value.splice(index, 1);
};

/**
 * 验收数据 tree
 */
const templateTree = ref<any[]>([]);
const fieldNames = { value: "standardId", label: "standardName" };
const getTree = (tree: any[]): any[] => {
  tree.forEach(v => {
    if (v.children && Array.isArray(v.children)) {
      for (let i = 0; i < v.children.length; i++) {
        const child = v.children[i];
        delete child.children;
      }
    }
  });
  return tree;
};
const getTemplateTree = async () => {
  const { data } = await standardTemplateTree();
  templateTree.value = getTree(data);
};
/**
 * 是否验收级联选择器
 * TODO：网上复制的，虽然不怎么样，将就用
 */
let nodes: any[] = [];
const getParentNodesByChildrenId = (his: any[], targetId: string, tree: any[]) => {
  tree.some(list => {
    const children = list.children || [];
    if (list.standardId === targetId) {
      nodes = his;
      return true;
    } else if (children.length > 0) {
      const history = [...his];
      history.push(list);
      return getParentNodesByChildrenId(history, targetId, children);
    }
  });
};
const getParentNodes = (id: string, tree: any[]) => {
  getParentNodesByChildrenId([], id, tree);
  return nodes;
};
const changeAcceptance = (value: string) => {
  const ids = getParentNodes(value, templateTree.value);
  if (ids?.length) {
    return (processForm.value.modelId = ids[0].standardId);
  }
  processForm.value.modelId = "";
  processForm.value.standardId = "";
};

/**
 * 提交任务
 */
const handelSubmitTaskOk = async () => {
  const valid = await proxy.$refs.processFormRef?.validate();
  if (valid) return Message.error("请填写完整信息");
  const postData = cloneDeep(processForm.value);
  postData.intervalDays = postData.intervalDays ?? 0;
  postData.trackDays = postData.trackDays ?? 0;
  let checkTypeLable: string[] = [];
  (postData.checkType as []).forEach((v: any) => {
    checkTypeLable.push(v === 1 ? "内部" : "客户");
  });
  postData.isCheck = checkTypeLable?.length ? 1 : 0;
  const paramsData = {
    ...postData,
    packageId: stageDetail.value.packageId,
    portraitId: stageDetail.value.portraitId,
    stageSettingId: stageDetail.value.stageSettingId,
    checkType: checkTypeLable.join(",")
  };
  paramsData.taskTriggerConditionSettings = preConditionList.value;

  if (paramsData.taskSettingId) {
    await templateApi.editTask(paramsData, paramsData.taskSettingId);
  } else {
    await templateApi.addTask(paramsData);
  }
  Message.success("操作成功");
  getTaskList(stageDetail.value.packageId);
  handelCloseTaskDrawer();
};
const handelCloseTaskDrawer = async () => {
  await nextTick();
  proxy.$refs.processFormRef.resetFields();
  processForm.value = { ...initProcessData };
  preConditionList.value = [];
  isShowTaskOption.value = false;
};

const initPage = async () => {
  const { data } = await templateApi.listTemplate();
  templateList.value = data ?? [];
  if (data?.length) {
    activePackageId.value = data[0]?.packageId || "";
    stageDetail.value = cloneDeep(data[0]);
    // getFlowList();
    getTaskList(data[0].packageId);
  }
};
/**
 * 参考数据
 */
const showReferenceDialog = ref(false);
const taskSettingId = ref("");
const handleReferenceData = (record: any) => {
  showReferenceDialog.value = true;
  taskSettingId.value = record.taskSettingId;
};
const handleReferenceClose = () => {
  showReferenceDialog.value = false;
};
getLeaderList();
initPage();
</script>

<style scoped lang="scss">
@import "taskTemplate";

:deep(.arco-table-header) th {
  background-color: #f2f6fc !important;
}

:deep(.arco-table-body) tr:nth-child(2n) td {
  background-color: #f5f7fa !important;
}
</style>
